# 用户账户相关功能
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.generic import View
from web.forms.account import RegisterModelForm, SendSmsForm, LoginForm
from web import models
from utils.tencent.sms import send_sms_single
import random
import logging
import uuid
import datetime
from django.conf import settings
from PIL import Image, ImageDraw, ImageFont
import io
import string

# 配置日志
logger = logging.getLogger(__name__)


def image_code(request):
    """生成图片验证码"""
    # 定义图片的宽和高
    width, height = 120, 40
    # 创建一个图片对象
    image = Image.new('RGB', (width, height), color='white')
    # 创建一个画笔对象
    draw = ImageDraw.Draw(image)
    # 定义字体
    try:
        font = ImageFont.truetype('arial.ttf', 28)
    except IOError:
        # 如果找不到arial.ttf，使用默认字体
        font = ImageFont.load_default()
    # 生成随机字符串作为验证码
    chars = string.ascii_uppercase + string.digits
    code = ''.join(random.choices(chars, k=4))
    # 将验证码保存到session中
    request.session['image_code'] = code
    request.session.set_expiry(300)  # 5分钟过期
    # 在图片上绘制验证码
    for i, char in enumerate(code):
        draw.text((20 + i * 25, 5), char, font=font, fill=(random.randint(0, 150), random.randint(0, 150), random.randint(0, 150)))
    # 绘制干扰线
    for _ in range(5):
        draw.line([(random.randint(0, width), random.randint(0, height)),
                   (random.randint(0, width), random.randint(0, height))],
                  fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),
                  width=1)
    # 绘制干扰点
    for _ in range(50):
        draw.point([(random.randint(0, width), random.randint(0, height))],
                   fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
    # 将图片保存到内存中
    buffer = io.BytesIO()
    image.save(buffer, 'png')
    # 返回图片
    return HttpResponse(buffer.getvalue(), content_type='image/png')


def login(request):
    """用户登录视图"""
    # 实例化表单
    form = LoginForm()
    if request.method == 'GET':
        return render(request, 'login.html', {'form': form})
    elif request.method == 'POST':
        # 处理AJAX POST请求
        logger.debug('登录请求数据: %s', request.POST)
        form = LoginForm(data=request.POST, request=request)
        if form.is_valid():
            try:
                # 获取验证通过的用户对象
                user = form.cleaned_data['user']
                # 登录用户
                from django.contrib.auth import login as auth_login
                auth_login(request, user)
                logger.info('用户登录成功: %s', user.username)
                return JsonResponse({'status': True, 'message': '登录成功'})
            except Exception as e:
                logger.error('用户登录失败: %s', str(e))
                return JsonResponse({'status': False, 'error': f'登录失败: {str(e)}'})
        else:
            # 表单验证失败
            errors = {} 
            for field, error_list in form.errors.items():
                errors[field] = error_list[0]
            logger.warning('表单验证失败: %s', errors)
            return JsonResponse({'status': False, 'error': errors})
    return JsonResponse({'status': False, 'error': '不支持的请求方法'})


def register(request):
    """用户注册视图"""
    # 实例化表单
    form = RegisterModelForm()
    if request.method == 'GET':
        return render(request, 'register.html', {'form': form})
    elif request.method == 'POST':
        # 处理AJAX POST请求
        logger.debug('注册请求数据: %s', request.POST)
        form = RegisterModelForm(data=request.POST)
        if form.is_valid():
            # 获取验证码
            code = request.POST.get('code')
            # 修改为固定验证码0000通过
            # sms_code = request.session.get('sms_code')

            if code != '0000':
                logger.warning('验证码错误: %s', code)
                return JsonResponse({'status': False, 'error': '验证码错误，正确验证码为0000'})

            try:
                # 使用表单的save方法，该方法已经包含密码加密逻辑
                user = form.save()
                logger.info('用户注册成功: %s', user.username)

                # 创建交易记录
                policy_object = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
                if policy_object:
                    models.Transaction.objects.create(
                        status=2,
                        order=str(uuid.uuid4()),
                        user=user,
                        price_policy=policy_object,
                        count=0,
                        price=0,
                        start_datetime=datetime.datetime.now()
                    )
                    logger.info('为用户 %s 创建了免费版交易记录', user.username)

                return JsonResponse({'status': True, 'message': '注册成功'})
            except Exception as e:
                logger.error('用户保存失败: %s', str(e))
                return JsonResponse({'status': False, 'error': f'注册失败: {str(e)}'})
        else:
            # 表单验证失败
            errors = {}
            for field, error_list in form.errors.items():
                errors[field] = error_list[0]
            logger.warning('表单验证失败: %s', errors)

            return JsonResponse({'status': False, 'error': errors})
    return JsonResponse({'status': False, 'error': '不支持的请求方法'})


def send_sms(request):
    """ 发送短信 """
    form = SendSmsForm(data=request.GET, request=request)
    if form.is_valid():
        # 表单验证通过，获取手机号
        mobilephone = form.cleaned_data['mobilephone']
        # 生成随机验证码
        code = str(random.randint(1000, 9999))
        # 获取短信模板ID
        tpl = request.GET.get('tpl')
        template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl, '123456')  # 默认模板ID
        # 发送短信
        result = send_sms_single(mobilephone, template_id, [code])
        # 返回响应
        if result['result'] == 0:
            # 可以将验证码存储到session中，用于后续验证
            request.session['sms_code'] = code
            request.session.set_expiry(300)  # 5分钟过期
            return JsonResponse({'status': True, 'message': '短信发送成功'})
        else:
            return JsonResponse({'status': False, 'error': f'发送短信失败：{result["errmsg"]}'})

    return JsonResponse({'status': False, 'error': form.errors})
